#include "vl_props.h"
#include "vl_prop_file_reader.h"

using namespace VL;


VLPropFileReader::VLPropFileReader(const std::string& filePath): input(filePath) {
	if(this->input.fail()) {
		throw VLPropExcetion(VL_PROP_ERROR_READ_OPEN, "cannot open file %s", filePath.c_str());
	}
}
VLPropFileReader::~VLPropFileReader() {
	this->input.close();
}

void VLPropFileReader::readLine(std::string& line) {
	if(this->input.eof() || this->input.fail()) {
		throw VLPropExcetion(VL_PROP_ERROR_READ_EOF, "reach eof of file");
	}
	std::getline(this->input, line);
}

const bool VLPropFileReader::isEof() const {
	return this->input.eof();
}

uint8_t VLPropFileReader::read() {
	if(this->input.eof() || this->input.fail()) {
		throw VLPropExcetion(VL_PROP_ERROR_READ_EOF, "reach eof of file");
	}
	
	uint8_t byte;
	this->input.read((char *)&byte, 1);
	return byte;
}

size_t VLPropFileReader::readBuf(uint8_t* buf, size_t bufLength) {
	if(this->input.eof() || this->input.fail()) {
		throw VLPropExcetion(VL_PROP_ERROR_READ_EOF, "reach eof of file");
	}
	auto extracted = this->input.read((char *)buf, bufLength).gcount();
	if(extracted != bufLength) {
		throw VLPropExcetion(VL_PROP_ERROR_READ_BUF, "read buffer failed");
	}
	return bufLength;
}